import { getCurrentInstance, onBeforeUnmount, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import page from './page.ts';
export function useListComponent() {
  const router = useRouter();
  const route = useRoute();
  const { proxy } = getCurrentInstance() as any;
  //页面信息
  const dataInfo: any = reactive({
    loading: false, //加载
    loadingMsg: '列表数据加载中', //加载
    table: {
      title: page.title, //表格-标题
      //表格-内容数据
      tbody: [],
      rowKey: 'produceTaskBillNo',
      theadCode: 'producetaskbilllist', //basedatatable
      //表格-表头数据
      thead: [],
      selectArr: [],
      //表格-搜索数据
      search: {
        pageIndex: 1, //当前页码
        pageSize: 30, //每页显示数据的数量
        totalCount: 0, //总数量
        queryDataBaseFiled: 'produceTaskBillNo',
        likeWords: '',
        isShowCancelBills: false,
        isShowCompleteBills: true,
        produceBillType: 0, //生产单据类型：1生产开单；2生产补单；其他待定，0查询全部
        produceBillState: -1, //生产任务单状态
        taskProduceState: -1, //任务单生产状态：0待生产；1生产中；2待停工；3已停工；4已完成（缴库单确认后就算生产任务已完成），-1查询全部
        materialState: -1, //领料状态
        dataBillState: -2, //-2查询全部，-1无，0未到达1已到达；2制作中；3已完成
        beginTime: '',
        endTime: '',
      },
      //多选
      checkbox: {
        state: true,
        selectable: (row: any) => {
          return true;
        },
        list: [],
      },
      //表格-按钮数据
      btns: [
        {
          title: '导出数据',
          icon: 'Download',
          type: '',
          children: [
            {
              title: '导出当页数据',
              click: () => {
                setLoading('导出当页数据,请稍等');
                exportBtn(dataInfo.table.tbody);
              },
            },
            {
              title: '导出全部数据',
              click: () => {
                setLoading('正在导出全部数据,请稍等');
                proxy.$api.ProductionBusniess.GetMatchPageProduceTaskBills({
                  ...dataInfo.table.search,
                  pageIndex: 1,
                  pageSize: 1000,
                  // beginTime: dataInfo.table.search.beginTime || proxy.$getTimeAgo(1, 'years'), // 开始时间
                  // endTime: dataInfo.table.search.endTime || proxy.$day(new Date()), // 结束时间
                })
                  .then((res: any) => {
                    exportBtn(res.list);
                  })
                  .catch(() => {
                    dataInfo.loading = false;
                  });
              },
            },
            {
              title: '导出选中数据',
              click: () => {
                setLoading('导出选中数据,请稍等');
                exportBtn(dataInfo.table.checkbox.list);
              },
            },
          ],
        },
        {
          title: '生产排程',
          click: () => {
            const thead: any[] = [
              {
                label: '生产编号',
                prop: 'produceTaskBillNo',
                align: 'center',
              },
              {
                label: '下单日期',
                prop: 'createDate',
                align: 'center',
              },
              {
                label: '客户',
                prop: 'customerName',
                align: 'left',
              },
              {
                label: '协议书号',
                prop: 'xieYiShuHao',
                align: 'center',
              },
              {
                label: '产品名称',
                prop: 'orderProductName',
                align: 'left',
              },
              {
                label: '产品编号',
                prop: 'productNo',
                align: 'center',
              },
              {
                label: '数量',
                prop: 'orderTagQuantity',
                align: 'center',
              },
              {
                label: '米数',
                prop: 'plannedMaterials',
                align: 'center',
              },
              {
                label: '交期',
                prop: 'deliveryDate',
                align: 'center',
              },
              {
                label: '是否结单',
                prop: 'craftTaskStateName',
                align: 'center',
              },
              {
                label: '刀版信息',
                prop: 'knifeInformation',
                align: 'left',
              },
              {
                label: '工序',
                prop: 'index',
                align: 'center',
              },
              {
                label: '工艺',
                prop: 'craftName',
                align: 'center',
              },
              {
                label: '设备',
                prop: 'machineName',
                align: 'center',
              },
              {
                label: '开机速度',
                prop: 'value3',
                align: 'left',
              },
              {
                label: '已生产量',
                prop: 'value1',
                align: 'left',
              },
              {
                label: '待排单量',
                prop: 'value2',
                align: 'left',
              },
            ];
            let tbody: any[] = [];
            const _table = dataInfo.table;
            const _craftTaskState: any = {
              1: '生产中',
              2: '已完成',
              3: '分批中',
            };
            if (_table.checkbox.list.length > 0) {
              tbody = _table.checkbox.list;
            } else {
              tbody = _table.tbody.filter((el: any) => ['待生产', '生产中'].includes(el.taskProduceStateName) && ['已确认'].includes(el.produceBillStateName));
            }
            tbody = tbody
              .sort((rowA: any, rowB: any) => {
                return new Date(rowA.createDate).getTime() - new Date(rowB.createDate).getTime();
              })
              .flatMap((el: any) =>
                el.productionProgressList.map((list: any, listIndex: number) => ({
                  ...el,
                  produceTaskBillNo: el.produceTaskBillNo, //生产编号
                  createDate: proxy.$day(el.createDate, 'YYYY/MM/DD'), //下单日期
                  customerName: el.customerName, //客户
                  xieYiShuHao: el.xieYiShuHao, //协议书号
                  orderProductName: el.orderProductName, //产品名称
                  productNo: el.productNo, //产品编号
                  orderTagQuantity: el.orderTagQuantity, //数量
                  plannedMaterials: el.plannedMaterials, //米数
                  knifeInformation: el.knifeInformation, //刀版信息
                  deliveryDate: proxy.$day(el.deliveryDate, 'YYYY/MM/DD'), //交期
                  craftTaskStateName: _craftTaskState[el.craftTaskStateName] || '待生产', //是否结单
                  value1: '', //已生产量
                  value2: '', //待排单量
                  index: listIndex + 1, //工序
                  craftName: list.craftName, //工艺
                  machineName: list.machineName, //设备
                  value3: '', //开机速度
                })),
              );
            exportBtn(tbody, thead, '生产排程', 'produceTaskBillNo', [
              'produceTaskBillNo', //
              'createDate',
              'customerName',
              'xieYiShuHao',
              'orderProductName',
              'productNo',
              'orderTagQuantity',
              'plannedMaterials',
              'deliveryDate',
              'craftTaskStateName',
              'knifeInformation',
            ]);
          },
        },
      ],
      //表格-列表搜索
      operation: [
        {
          title: '查看',
          hidden: (row: any) => {
            return row.produceBillState === 0;
          },
          click: (row: any) => {
            editBtn(row, 3);
          },
        },
        {
          title: '编辑',
          hidden: (row: any) => {
            return row.produceBillState !== 0;
          },
          click: (row: any) => {
            editBtn(row, 2);
          },
        },
        {
          title: '确认',
          disabled: (row: any) => {
            return ![0].includes(row.produceBillState);
          },
          click: (row: any) => {
            proxy.$messageBox('是否确认当前数据，请确认！', () => {
              proxy.$api.ProductionBusniess.SureProduceTaskBill({
                produceTaskID: row.produceTaskID,
              })
                .then((res: any) => {
                  proxy.$message('确认成功');
                  getTbody();
                })
                .catch(() => {});
            });
          },
        },
        {
          title: '撤回',
          disabled: (row: any) => {
            return ![1].includes(row.produceBillState) || ![0].includes(row.taskProduceState);
          },
          click: (row: any) => {
            proxy.$messageBox('是否撤回当前数据，请确认！', () => {
              proxy.$api.ProductionBusniess.RevocationProduceTaskBill({
                produceTaskID: row.produceTaskID,
              })
                .then((res: any) => {
                  proxy.$message('撤回成功');
                  getTbody();
                })
                .catch(() => {});
            });
          },
        },
        {
          title: '生产补单',
          disabled: (row: any) => {
            return ![1].includes(row.produceBillState) || [0].includes(row.taskProduceState);
          },
          click: (row: any) => {
            proxy.$messageBox(`是否对【${row.orderProductName}】进行补单，请确认`, () => {
              proxy.$api.ProductionBusniess.CopyCreateProduceTaskBill({
                produceTaskBillNo: row.produceTaskBillNo,
              })
                .then((res: any) => {
                  proxy.$message('生产补单创建成功');
                  dataInfo.table.search.pageIndex = 1;
                  getTbody();
                })
                .catch(() => {});
            });
          },
        },
        {
          title: '生产状态',
          children: [
            {
              title: '生产中',
              disabled: (row: any) => {
                return [0, 2].includes(row.produceBillState) || [1].includes(row.taskProduceState);
              },
              click: (row: any) => {
                proxy.$messageBox(`是否将生产单状态改为生产中，请确认`, () => {
                  proxy.$api.ProductionBusniess.RevokeFinishedProduceTaskBill({
                    produceTaskID: row.produceTaskID,
                  })
                    .then((res: any) => {
                      proxy.$message('修改成功');
                      getTbody();
                    })
                    .catch(() => {});
                });
              },
            },
            {
              title: '完工',
              disabled: (row: any) => {
                return [0, 2].includes(row.produceBillState) || [4].includes(row.taskProduceState);
              },
              click: (row: any) => {
                proxy.$messageBox(`${row.progress != 100 ? '生产单下还有未完成的作业是，否继续完成！' : '是否将生产单状态改为完工，请确认'}`, () => {
                  proxy.$api.ProductionBusniess.FinishedProduceTaskBill({
                    produceTaskID: row.produceTaskID,
                  })
                    .then((res: any) => {
                      proxy.$message('修改成功');
                      getTbody();
                    })
                    .catch(() => {});
                });
              },
            },
            {
              title: '停工',
              disabled: (row: any) => {
                return [0, 2].includes(row.produceBillState) || [3].includes(row.taskProduceState);
              },
              click: (row: any) => {
                proxy.$messageInputBox(`请填写停工原因`, (value: string) => {
                  proxy.$api.ProductionBusniess.StopProduceTaskBill({
                    produceTaskID: row.produceTaskID,
                    cancelReason: value,
                  })
                    .then((res: any) => {
                      proxy.$message('修改成功');
                      getTbody();
                    })
                    .catch(() => {});
                });
              },
            },
          ],
        },
        {
          title: '生产通知单',
          children: [
            {
              title: '打印',
              disabled: (row: any) => {
                return [0, 2].includes(row.produceBillState);
              },
              click: (row: any) => {
                handleDownload(row, 1);
              },
            },
            {
              title: '预览',
              disabled: (row: any) => {
                return [0, 2].includes(row.produceBillState);
              },
              click: (row: any) => {
                handleDownload(row, 2);
              },
            },
            {
              title: '下载',
              disabled: (row: any) => {
                return [0, 2].includes(row.produceBillState);
              },
              click: (row: any) => {
                handleDownload(row, 3);
              },
            },
          ],
        },
        {
          title: '工序质量流转卡',
          children: [
            {
              title: '打印',
              disabled: (row: any) => {
                return [0, 2].includes(row.produceBillState);
              },
              click: (row: any) => {
                handleDownloadCard(row, 1);
              },
            },
            {
              title: '下载',
              disabled: (row: any) => {
                return [0, 2].includes(row.produceBillState);
              },
              click: (row: any) => {
                handleDownloadCard(row, 3);
              },
            },
          ],
        },
        {
          title: '作废',
          disabled: (row: any) => {
            return ![0].includes(row.produceBillState);
          },
          click: (row: any) => {
            proxy.$messageInputBox('请填写作废原因！', (value: string) => {
              proxy.$api.ProductionBusniess.ScrapProduceTaskBill({
                produceTaskID: row.produceTaskID,
                cancelReason: value,
              })
                .then((res: any) => {
                  proxy.$message('作废成功!');
                  getTbody();
                })
                .catch(() => {});
            });
          },
        },
      ],
    },
    tableAdd: {
      tbody: [],
      thead: [
        {
          label: '订单单号',
          prop: 'orderNo',
          align: 'center',
          width: 140,
        },
        {
          label: '协议书号',
          prop: 'xieYiShuHao',
          align: 'center',
          width: 140,
        },
        {
          label: '订单类型',
          prop: 'orderTypeName',
          align: 'center',
          width: 120,
        },
        {
          label: '客户名称',
          prop: 'customerName',
          align: 'center',
          width: 240,
        },
        {
          label: '交货日期',
          prop: 'expectedDeliveryTime',
          align: 'center',
          width: 120,
        },
        {
          label: '交货剩余天数',
          prop: 'deliveryDays',
          align: 'center',
          width: 160,
        },
        {
          label: '产品编号',
          prop: 'productCode',
          align: 'center',
          width: 190,
        },
        {
          label: '产品名称',
          prop: 'orderProductName',
          align: 'left',
          width: null,
        },
        {
          label: '版本',
          prop: 'productVersions',
          align: 'center',
          width: 100,
        },
        {
          label: '版面',
          prop: 'printingSurface',
          align: 'center',
          width: 100,
        },
        {
          label: '单位',
          prop: 'productUnion',
          align: 'center',
          width: 100,
        },
        {
          label: '订单数量',
          prop: 'orderNum',
          align: 'center',
          width: 100,
        },
        {
          label: '标签枚数',
          prop: 'tagSumQuantity',
          align: 'center',
          width: 100,
        },
        {
          label: '库存余量',
          prop: 'stockNum',
          align: 'center',
          width: 100,
        },
        {
          label: '开单时间',
          prop: 'orderCreateTime',
          align: 'center',
          width: 180,
        },
        {
          label: '开单人员',
          prop: 'createOrderPerson',
          align: 'center',
          width: 100,
        },
      ],
      pup: {
        state: false,
        width: 400,
        height: 'auto',
        title: '选择开单类型',
        form: {
          produceBillType: '', //生产单类型
          saleOrderNo: '', //销售单号
          oldSaleOrderNo: '', //老订单号
        },
        orderType: [
          {
            label: '生产开单',
            value: 1,
          },
          {
            label: '测试开单',
            value: 3,
          },
          {
            label: '调机开单',
            value: 4,
          },
          {
            label: '打样开单',
            value: 5,
          },
          {
            label: '委外生产',
            value: 6,
          },
          {
            label: '库存提货',
            value: 7,
          },
        ],
        clickBtn: (row: any) => {
          let _pup = dataInfo.tableAdd.pup;
          proxy.$api.ProductionBusniess.AutoCreateProduceTaskBill({
            ..._pup.form,
            produceBillType: row.value,
          })
            .then((res: any) => {
              proxy.$message('生产单创建成功!');
              _pup.state = false;
              editBtn(res, 2);
              getTbody();
            })
            .catch(() => {});
        },
      },
      getTbody: (table: any) => {
        proxy.$api.OrderBusniess.GetPageSaleOrdersByPassingColorDraft({
          pageIndex: 1,
          pageSize: 200,
          queryDataBaseFiled: '',
          likeWords: '',
          orderType: '',
          customerCode: '',
          orderState: 0,
          produceState: 0,
          financeState: 0,
          deliveryState: 0,
          queryCondition: 0,
        })
          .then((res: any) => {
            table.tbody = res.list;
          })
          .catch(() => {});
      },
      selectBtn: (row: any) => {
        let _pup = dataInfo.tableAdd.pup;
        _pup.state = true;
        _pup.form.saleOrderNo = row.saleOrderCode;
      },
    },
    options: {
      //单据状态
      produceBillState: [
        {
          label: '全部',
          value: -1,
        },
        {
          label: '待确认',
          value: 0,
          type: 'info',
        },
        {
          label: '已确认',
          value: 1,
          type: 'success',
        },
        {
          label: '已作废',
          value: 2,
          type: 'warning',
        },
      ],
      //数据状态
      dataBillState: [
        {
          label: '全部',
          value: -2,
        },
        {
          label: '无数据',
          value: -1,
          type: 'warning',
        },
        {
          label: '未到达',
          value: 0,
          type: 'info',
        },
        {
          label: '已到达',
          value: 1,
        },
        {
          label: '制作中',
          value: 2,
        },
        {
          label: '已完成',
          value: 3,
          type: 'success',
        },
      ],
      //生产状态
      taskProduceState: [
        {
          label: '全部',
          value: -1,
        },
        {
          label: '待生产',
          value: 0,
          type: 'info',
        },
        {
          label: '生产中',
          value: 1,
        },
        {
          label: '待停工',
          value: 2,
          type: 'warning',
        },
        {
          label: '已停工',
          value: 3,
          type: 'danger',
        },
        {
          label: '已完成',
          value: 4,
          type: 'success',
        },
      ],
      //领料状态
      materialState: [
        {
          label: '全部',
          value: -1,
        },
        {
          label: '待领料',
          value: 0,
          type: 'info',
        },
        {
          label: '已领料',
          value: 1,
          type: 'success',
        },
        {
          label: '已出库',
          value: 2,
          type: 'success',
        },
      ],
      //打印状态
      noticeBillDownloaded: [
        {
          label: '待打印',
          value: '否',
          type: 'info',
        },
        {
          label: '已打印',
          value: '是',
          type: 'success',
        },
      ],
      //印刷版面
      printingSurface: [
        {
          label: '新版',
          value: '新版',
          type: 'danger',
        },
        {
          label: '改版',
          value: '改版',
          type: 'warning',
        },
        {
          label: '老版',
          value: '老版',
          type: 'success',
        },
      ],
      machine: [],
      produceCraft: [],
    },
  });
  //编辑
  const editBtn = (row: any, type: number = 3) => {
    getPath({
      path: `${route.path}/details`,
      query: {
        type: type, //页面类型
        produceTaskBillNo: row.produceTaskBillNo, //生产单号
      },
    });
  };
  //打印单据
  const handleDownload = (row: any, printType = 1) => {
    setLoading('正在打印单据,请稍等');
    let _form = {
      templateTypeCode: 'MBLX0002', //	模板类型编号
      customerCode: row.customerCode, //	客户编号
      condition: {
        ProductCode: row.productCode, //产品编号
        SaleOrderCode: row.saleOrderCode,
        ProduceTaskBillNo: row.produceTaskBillNo,
      }, //查询条件
    };
    if (printType === 3) {
      proxy.$api.Public.DownLoadTemplateExcel(_form)
        .then((res: any) => {
          window.open(res, '_blank');
          dataInfo.loading = false;
        })
        .catch(() => {
          dataInfo.loading = false;
        });
    } else {
      proxy.$api.Public.DownLoadTemplate(_form)
        .then((res: any) => {
          if (printType === 1) {
            //更新生产单打印状态
            proxy.$api.ProductionBusniess.UpdateProduceNoticeBillDownloaded({
              produceTaskBillNo: row.produceTaskBillNo,
            })
              .then((res: any) => {
                proxy.$message('打印成功!');
                getTbody();
              })
              .catch(() => {
                dataInfo.loading = false;
              });
          }
          window.open(res, '_blank');
          dataInfo.loading = false;
        })
        .catch(() => {
          dataInfo.loading = false;
        });
    }
  };
  //打印
  const handleDownloadCard = (row: any, printType = 1) => {
    proxy.$DownLoadTemp(
      {
        templateTypeCode: 'MBLX0003', //	模板类型编号
        customerCode: row.customerCode, //	客户编号
        condition: {
          ProduceTaskBillNo: row.produceTaskBillNo,
        }, //查询条件
      },
      printType,
      dataInfo,
    );
  };
  // 获取tabs数据
  const getPath = (obj: any, row?: any) => {
    const path = router.resolve(obj);
    // 在新窗口或标签页中打开目标路径
    const newWindow: any = window.open(path.href, '_blank');
    newWindow;
  };
  // 获取表数据
  const getTbody = () => {
    let _table: any = dataInfo.table;
    setLoading();
    proxy.$api.ProductionBusniess.GetMatchPageProduceTaskBills({
      ..._table.search,
    })
      .then((res: any) => {
        _table.tbody = res.list;
        _table.search.totalCount = res.totalCount;
        dataInfo.loading = false;
      })
      .catch(() => {
        dataInfo.loading = false;
      });
    let _tableAdd: any = dataInfo.tableAdd;
    if (_tableAdd && proxy.$isFunction(_tableAdd.getTbody)) {
      _tableAdd.getTbody(_tableAdd);
    }
  };
  // 导出数据
  const exportBtn = (tbody: any[], thead?: any[], title: string = dataInfo.table.title, mergeCode?: string, mergeCodeArr?: any[]) => {
    proxy.$exportData(
      {
        thead: thead || dataInfo.table.thead,
        tbody: JSON.parse(JSON.stringify(tbody)).sort((rowA: any, rowB: any) => new Date(rowA.createDate).getTime() - new Date(rowB.createDate).getTime()),
        fileName: title,
        mergeCode: mergeCode,
        mergeCodeArr: mergeCodeArr,
      },
      dataInfo,
    );
    setTimeout(() => {
      dataInfo.loading = false;
    }, 1000);
  };
  const setLoading = (title: string = '正在获取数据,请稍等...') => {
    if (!dataInfo.loading) {
      dataInfo.loading = true;
      dataInfo.loadingMsg = title;
    }
  };
  // 组件挂载后执行
  onMounted(() => {
    getTbody();
  });
  // 组件卸载前执行
  onBeforeUnmount(() => {});
  return { dataInfo, getTbody, setLoading };
}
